'use client';

import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  DatePicker, 
  Select, 
  message, 
  Space, 
  Popconfirm,
  Card,
  Row,
  Col,
  InputNumber,
  Tabs,
  Divider,
  Tag,
  Tooltip,
  Spin,
  Typography,
  Descriptions
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  QrcodeOutlined, 
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import AdminLayout from '@/components/AdminLayout';
import ProductSelect from '@/components/ProductSelect';
import { request } from '@/utils/request';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;
const { Text } = Typography;

interface TraceabilityRecord {
  id: number;
  batchNumber: string;
  productId: number;
  productName: string;
  fishingVessel: string;
  fishingLocation: string;
  fishingCoordinates: string;
  fishingDate: string;
  fishingMethod: string;
  processingFacility: string;
  processingDate: string;
  freezingMethod: string;
  qualityCertificate: string;
  inspectionReport: string;
  transportCompany: string;
  transportTemperature: string;
  qrCode: string;
  qrCodeUrl: string;
  createdAt: string;
  updatedAt: string;
}

const TraceabilityManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [traceabilityList, setTraceabilityList] = useState<TraceabilityRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchForm] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [editingRecord, setEditingRecord] = useState<TraceabilityRecord | null>(null);
  const [qrModalVisible, setQrModalVisible] = useState(false);
  const [qrCodeUrl, setQrCodeUrl] = useState('');
  const [form] = Form.useForm();
  const [activeTab, setActiveTab] = useState('1');
  const [previewRecord, setPreviewRecord] = useState<TraceabilityRecord | null>(null);
  const [previewModalVisible, setPreviewModalVisible] = useState(false);

  // 获取溯源列表
  const fetchTraceabilityList = async (page = 1, size = 10, params = {}) => {
    setLoading(true);
    try {
      const response = await request.post('/trace/query', {
        page: page - 1,
        size,
        ...params
      });

      if (response.code === 200) {
        setTraceabilityList(response.data.content || []);
        setTotal(response.data.totalElements || 0);
      } else {
        message.error('获取溯源列表失败: ' + response.message);
      }
    } catch (error) {
      console.error('获取溯源列表错误:', error);
      message.error('获取溯源列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 搜索
  const handleSearch = async () => {
    try {
      const values = await searchForm.validateFields();
      const params = {
        ...values,
        fishingDateStart: values.fishingDate?.[0] ? dayjs(values.fishingDate[0]).format('YYYY-MM-DD') : undefined,
        fishingDateEnd: values.fishingDate?.[1] ? dayjs(values.fishingDate[1]).format('YYYY-MM-DD') : undefined,
      };
      delete params.fishingDate;
      fetchTraceabilityList(1, pageSize, params);
    } catch (error) {
      console.error('搜索验证失败:', error);
    }
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    fetchTraceabilityList(1, pageSize);
  };

  // 分页变化
  const handlePageChange = (page: number, size?: number) => {
    setCurrentPage(page);
    const newPageSize = size || pageSize;
    setPageSize(newPageSize);
    fetchTraceabilityList(page, newPageSize, searchForm.getFieldsValue());
  };

  // 显示创建/编辑模态框
  const showModal = (record?: TraceabilityRecord) => {
    if (record) {
      setModalTitle('编辑溯源信息');
      setEditingRecord(record);
      form.setFieldsValue({
        ...record,
        fishingDate: record.fishingDate ? dayjs(record.fishingDate) : null,
        processingDate: record.processingDate ? dayjs(record.processingDate) : null,
      });
    } else {
      setModalTitle('创建溯源信息');
      setEditingRecord(null);
      form.resetFields();
    }
    setModalVisible(true);
  };

  // 关闭模态框
  const handleModalCancel = () => {
    setModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleFinish = async (values: any) => {
    try {
      const payload = {
        ...values,
        fishingDate: values.fishingDate ? values.fishingDate.format('YYYY-MM-DD') : null,
        processingDate: values.processingDate ? values.processingDate.format('YYYY-MM-DD') : null,
      };

      let response;
      if (editingRecord) {
        // 编辑
        response = await request.put(`/trace/${editingRecord.id}`, payload);
      } else {
        // 创建
        response = await request.post('/trace', payload);
      }

      if (response.code === 200) {
        message.success(editingRecord ? '更新成功' : '创建成功');
        setModalVisible(false);
        form.resetFields();
        fetchTraceabilityList(currentPage, pageSize, searchForm.getFieldsValue());
      } else {
        message.error((editingRecord ? '更新失败: ' : '创建失败: ') + response.message);
      }
    } catch (error) {
      console.error('保存失败:', error);
      message.error(editingRecord ? '更新失败' : '创建失败');
    }
  };

  // 删除溯源记录
  const handleDelete = async (id: number) => {
    try {
      const response = await request.delete(`/trace/${id}`);
      if (response.code === 200) {
        message.success('删除成功');
        fetchTraceabilityList(currentPage, pageSize, searchForm.getFieldsValue());
      } else {
        message.error('删除失败: ' + response.message);
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 显示二维码
  const showQRCode = async (batchNumber: string) => {
    try {
      const response = await request.get(`/trace/qrcode-url/${batchNumber}`);
      if (response.code === 200) {
        setQrCodeUrl(response.data);
        setQrModalVisible(true);
      } else {
        message.error('获取二维码失败: ' + response.message);
      }
    } catch (error) {
      console.error('获取二维码失败:', error);
      message.error('获取二维码失败');
    }
  };

  // 生成批次号
  const generateBatchNumber = async (productId: number) => {
    if (!productId) {
      message.warning('请先选择产品');
      return;
    }
    
    try {
      const response = await request.post(`/trace/generate-batch/${productId}`);
      if (response.code === 200) {
        form.setFieldsValue({ batchNumber: response.data });
        message.success('批次号生成成功');
      } else {
        message.error('生成批次号失败: ' + response.message);
      }
    } catch (error) {
      console.error('生成批次号失败:', error);
      message.error('生成批次号失败');
    }
  };

  // 预览溯源信息
  const showPreview = (record: TraceabilityRecord) => {
    setPreviewRecord(record);
    setPreviewModalVisible(true);
  };

  // 刷新数据
  const handleRefresh = () => {
    fetchTraceabilityList(currentPage, pageSize, searchForm.getFieldsValue());
  };

  useEffect(() => {
    fetchTraceabilityList(1, pageSize);
  }, []);

  const columns = [
    {
      title: '批次号',
      dataIndex: 'batchNumber',
      key: 'batchNumber',
      fixed: 'left' as const,
      width: 150,
      render: (text: string) => (
        <Tooltip title="点击查看详细信息">
          <Tag color="blue" style={{ cursor: 'pointer' }} onClick={() => {
            const record = traceabilityList.find(item => item.batchNumber === text);
            if (record) showPreview(record);
          }}>
            {text || ''}
          </Tag>
        </Tooltip>
      ),
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text && text.length > 10 ? `${text.substring(0, 10)}...` : text || ''}</span>
        </Tooltip>
      ),
    },
    {
      title: '渔船',
      dataIndex: 'fishingVessel',
      key: 'fishingVessel',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text && text.length > 8 ? `${text.substring(0, 8)}...` : text || ''}</span>
        </Tooltip>
      ),
    },
    {
      title: '捕捞地点',
      dataIndex: 'fishingLocation',
      key: 'fishingLocation',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text && text.length > 10 ? `${text.substring(0, 10)}...` : text || ''}</span>
        </Tooltip>
      ),
    },
    {
      title: '捕捞日期',
      dataIndex: 'fishingDate',
      key: 'fishingDate',
      width: 120,
      render: (date: string) => date || '-',
    },
    {
      title: '加工设施',
      dataIndex: 'processingFacility',
      key: 'processingFacility',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text && text.length > 10 ? `${text.substring(0, 10)}...` : text || ''}</span>
        </Tooltip>
      ),
    },
    {
      title: '运输公司',
      dataIndex: 'transportCompany',
      key: 'transportCompany',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text && text.length > 10 ? `${text.substring(0, 10)}...` : text || ''}</span>
        </Tooltip>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      sorter: (a: TraceabilityRecord, b: TraceabilityRecord) => 
        new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 220,
      render: (_: any, record: TraceabilityRecord) => (
        <Space size="middle">
          <Tooltip title="预览">
            <Button 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => showPreview(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="primary" 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => showModal(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确认删除"
            description="确定要删除这条溯源记录吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                danger 
                icon={<DeleteOutlined />} 
                size="small"
              />
            </Tooltip>
          </Popconfirm>
          <Tooltip title="查看二维码">
            <Button 
              icon={<QrcodeOutlined />} 
              size="small"
              onClick={() => showQRCode(record.batchNumber)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout 
      selectedKey="5" 
      breadcrumbItems={[{ title: '溯源管理' }]}
    >
      <div style={{ padding: '24px' }}>
        <h1 style={{ marginBottom: '24px', fontSize: '24px', fontWeight: 'bold' }}>
          溯源管理
        </h1>

        {/* 搜索表单 */}
        <Card style={{ marginBottom: '24px' }}>
          <Tabs defaultActiveKey="1" onChange={setActiveTab}>
            <TabPane tab="搜索条件" key="1">
              <Form
                form={searchForm}
                layout="vertical"
                onFinish={handleSearch}
              >
                <Row gutter={24}>
                  <Col span={6}>
                    <Form.Item name="batchNumber" label="批次号">
                      <Input placeholder="请输入批次号" />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item name="productName" label="产品名称">
                      <Input placeholder="请输入产品名称" />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item name="fishingVessel" label="渔船">
                      <Input placeholder="请输入渔船名称" />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item name="fishingLocation" label="捕捞地点">
                      <Input placeholder="请输入捕捞地点" />
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={24}>
                  <Col span={12}>
                    <Form.Item name="fishingDate" label="捕捞日期范围">
                      <RangePicker style={{ width: '100%' }} />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <Form.Item>
                      <Space>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                          搜索
                        </Button>
                        <Button onClick={handleReset}>
                          重置
                        </Button>
                        <Button icon={<ReloadOutlined />} onClick={handleRefresh}>
                          刷新
                        </Button>
                      </Space>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </TabPane>
            <TabPane tab="使用说明" key="2">
              <div>
                <p><InfoCircleOutlined /> 在此页面可以管理产品的溯源信息，包括创建、编辑、删除和查看二维码等功能。</p>
                <p><InfoCircleOutlined /> 点击批次号标签可以快速预览溯源信息。</p>
                <p><InfoCircleOutlined /> 使用搜索功能可以快速查找特定的溯源记录。</p>
              </div>
            </TabPane>
          </Tabs>
        </Card>

        {/* 操作按钮 */}
        <div style={{ marginBottom: '16px' }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => showModal()}
          >
            新增溯源信息
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            style={{ marginLeft: '8px' }}
          >
            刷新
          </Button>
        </div>

        {/* 表格 */}
        <Table
          dataSource={traceabilityList}
          columns={columns}
          loading={loading}
          scroll={{ x: 1500 }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            onChange: handlePageChange,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          locale={{
            emptyText: (
              <div style={{ padding: '40px' }}>
                <InfoCircleOutlined style={{ fontSize: '48px', color: '#999' }} />
                <div style={{ marginTop: '16px' }}>暂无溯源数据</div>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={() => showModal()}
                  style={{ marginTop: '16px' }}
                >
                  新增溯源信息
                </Button>
              </div>
            )
          }}
        />

        {/* 创建/编辑模态框 */}
        <Modal
          title={modalTitle}
          open={modalVisible}
          onCancel={handleModalCancel}
          footer={null}
          width={900}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleFinish}
            initialValues={{
              fishingMethod: '拖网捕捞',
              freezingMethod: '超低温冷冻',
              transportTemperature: '-18°C'
            }}
          >
            <Divider orientation="left">基础信息</Divider>
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  name="productId"
                  label="产品"
                  rules={[{ required: true, message: '请选择产品' }]}
                >
                  <ProductSelect style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="batchNumber"
                  label="批次号"
                  rules={[{ required: true, message: '请输入批次号' }]}
                >
                  <Input 
                    placeholder="请输入批次号" 
                    suffix={
                      <Button 
                        type="link" 
                        size="small"
                        onClick={() => {
                          const productId = form.getFieldValue('productId');
                          if (productId) {
                            generateBatchNumber(productId);
                          } else {
                            message.warning('请先选择产品');
                          }
                        }}
                      >
                        生成
                      </Button>
                    }
                  />
                </Form.Item>
              </Col>
            </Row>

            <Divider orientation="left">捕捞信息</Divider>
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="fishingVessel" label="渔船">
                  <Input placeholder="请输入渔船名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="fishingLocation" label="捕捞地点">
                  <Input placeholder="请输入捕捞地点" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="fishingCoordinates" label="捕捞坐标">
                  <Input placeholder="请输入捕捞坐标" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="fishingDate" label="捕捞日期">
                  <DatePicker style={{ width: '100%' }} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="fishingMethod" label="捕捞方法">
                  <Select placeholder="请选择捕捞方法">
                    <Option value="拖网捕捞">拖网捕捞</Option>
                    <Option value="围网捕捞">围网捕捞</Option>
                    <Option value="钓捕">钓捕</Option>
                    <Option value="其他">其他</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Divider orientation="left">加工信息</Divider>
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="processingFacility" label="加工设施">
                  <Input placeholder="请输入加工设施" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="processingDate" label="加工日期">
                  <DatePicker style={{ width: '100%' }} />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="freezingMethod" label="冷冻方法">
                  <Select placeholder="请选择冷冻方法">
                    <Option value="超低温冷冻">超低温冷冻</Option>
                    <Option value="冷藏">冷藏</Option>
                    <Option value="冰鲜">冰鲜</Option>
                    <Option value="其他">其他</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Divider orientation="left">质检信息</Divider>
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="qualityCertificate" label="质量证书">
                  <Input placeholder="请输入质量证书编号或名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="inspectionReport" label="检验报告">
                  <Input placeholder="请输入检验报告编号或名称" />
                </Form.Item>
              </Col>
            </Row>

            <Divider orientation="left">运输信息</Divider>
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item name="transportCompany" label="运输公司">
                  <Input placeholder="请输入运输公司" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="transportTemperature" label="运输温度">
                  <Input placeholder="请输入运输温度" addonAfter="°C" />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  {editingRecord ? '更新' : '创建'}
                </Button>
                <Button onClick={handleModalCancel}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>

        {/* 二维码模态框 */}
        <Modal
          title="二维码"
          open={qrModalVisible}
          onCancel={() => setQrModalVisible(false)}
          footer={null}
          width={400}
        >
          <div style={{ textAlign: 'center' }}>
            {qrCodeUrl ? (
              <>
                <img 
                  src={qrCodeUrl} 
                  alt="二维码" 
                  style={{ maxWidth: '100%', height: 'auto' }} 
                />
                <div style={{ marginTop: '16px' }}>
                  <Text type="secondary">扫描二维码可查看溯源信息</Text>
                </div>
              </>
            ) : (
              <div style={{ padding: '40px' }}>
                <Spin />
                <div style={{ marginTop: '16px' }}>二维码加载中...</div>
              </div>
            )}
          </div>
        </Modal>

        {/* 预览模态框 */}
        <Modal
          title="溯源信息预览"
          open={previewModalVisible}
          onCancel={() => setPreviewModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setPreviewModalVisible(false)}>
              关闭
            </Button>,
            <Button 
              key="edit" 
              type="primary" 
              icon={<EditOutlined />}
              onClick={() => {
                setPreviewModalVisible(false);
                if (previewRecord) {
                  showModal(previewRecord);
                }
              }}
            >
              编辑
            </Button>
          ]}
          width={800}
        >
          {previewRecord && (
            <div>
              <Card title="基础信息" size="small" style={{ marginBottom: '16px' }}>
                <Row gutter={16}>
                  <Col span={12}>
                    <p><strong>批次号：</strong> {previewRecord.batchNumber}</p>
                    <p><strong>产品名称：</strong> {previewRecord.productName}</p>
                  </Col>
                  <Col span={12}>
                    <p><strong>创建时间：</strong> {previewRecord.createdAt}</p>
                    <p><strong>更新时间：</strong> {previewRecord.updatedAt}</p>
                  </Col>
                </Row>
              </Card>

              <Tabs defaultActiveKey="1">
                <TabPane tab="捕捞信息" key="1">
                  <Card size="small">
                    <Descriptions column={2} size="small" bordered>
                      <Descriptions.Item label="渔船">{(previewRecord?.fishingVessel || '未填写')}</Descriptions.Item>
                      <Descriptions.Item label="捕捞地点">{(previewRecord?.fishingLocation || '未填写')}</Descriptions.Item>
                      <Descriptions.Item label="捕捞坐标">{(previewRecord?.fishingCoordinates || '未填写')}</Descriptions.Item>
                      <Descriptions.Item label="捕捞日期">{(previewRecord?.fishingDate || '未填写')}</Descriptions.Item>
                      <Descriptions.Item label="捕捞方法">{(previewRecord?.fishingMethod || '未填写')}</Descriptions.Item>
                    </Descriptions>
                  </Card>
                </TabPane>
                <TabPane tab="加工信息" key="2">
                  <Card size="small">
                    <Descriptions column={2} size="small" bordered>
                      <Descriptions.Item label="加工设施">{(previewRecord?.processingFacility || '未填写')}</Descriptions.Item>
                      <Descriptions.Item label="加工日期">{(previewRecord?.processingDate || '未填写')}</Descriptions.Item>
                      <Descriptions.Item label="冷冻方法">{(previewRecord?.freezingMethod || '未填写')}</Descriptions.Item>
                    </Descriptions>
                  </Card>
                </TabPane>
                <TabPane tab="质检信息" key="3">
                  <Card size="small">
                    <Descriptions column={1} size="small" bordered>
                      <Descriptions.Item label="质量证书">
                        {previewRecord?.qualityCertificate ? (
                          <a href={previewRecord.qualityCertificate} target="_blank" rel="noopener noreferrer">
                            {previewRecord.qualityCertificate}
                          </a>
                        ) : (
                          '未上传'
                        )}
                      </Descriptions.Item>
                      <Descriptions.Item label="检验报告">
                        {previewRecord?.inspectionReport ? (
                          <a href={previewRecord.inspectionReport} target="_blank" rel="noopener noreferrer">
                            {previewRecord.inspectionReport}
                          </a>
                        ) : (
                          '未上传'
                        )}
                      </Descriptions.Item>
                    </Descriptions>
                  </Card>
                </TabPane>
                <TabPane tab="运输信息" key="4">
                  <Card size="small">
                    <Descriptions column={2} size="small" bordered>
                      <Descriptions.Item label="运输公司">{(previewRecord?.transportCompany || '未填写')}</Descriptions.Item>
                      <Descriptions.Item label="运输温度">{(previewRecord?.transportTemperature || '未填写')}</Descriptions.Item>
                    </Descriptions>
                  </Card>
                </TabPane>
              </Tabs>
            </div>
          )}
        </Modal>
      </div>
    </AdminLayout>
  );
};

export default TraceabilityManagement;